package com.augurit.common.common.http.kt.api

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn

/**
 *  author : yanghaozhang
 *  date : 2022/5/6 0:30
 *  description :
 */
class FlowApiImpl<Response, OutputData> private constructor(private val wrapped: IApiTask<Response, OutputData>) :
    IApiTask<Response, OutputData> by wrapped {

    suspend fun await(): Flow<OutputData> {
        return flow {
            val outputData: OutputData = doRequest()
            emit(outputData)
        }.flowOn(Dispatchers.IO).catch { cause ->
            cause.printStackTrace()
            emit(handleException(cause))
        }
    }

    companion object {
        fun <Response, OutputData> enableFor(task: IApiTask<Response, OutputData>): FlowApiImpl<Response, OutputData> {
            return FlowApiImpl(task)
        }
    }
}

fun <Response, OutputData> IApiTask<Response, OutputData>.flowable() = FlowApiImpl.enableFor(this)

suspend fun <Response, OutputData> IApiTask<Response, OutputData>.await() = flowable().await()
